package cn.chrilwe.pigpig.user.interceptor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
  * 身份令牌刷新
 * @author chrilwe
 * 2020-9-1
 */
public class RefreshTokenInterceptor implements HandlerInterceptor{
	
	private StringRedisTemplate stringRedisTemplate;
	
	public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		Cookie[] cookies = request.getCookies();
		if(cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				String name = cookie.getName();
				String accessToken = cookie.getValue();
				if(name.equals("pigpig_access_token")) {
					String str = stringRedisTemplate.opsForValue().get(accessToken);
					if(StringUtils.isNotEmpty(str)) {
						stringRedisTemplate.opsForValue().set(accessToken, str, 30, TimeUnit.MINUTES);
					}
				}
			}
		}
	}


}
